<template>
  <a-modal v-model:open="open"
           width="100%"
           wrap-class-name="full-modal"
           :keyboard="false"
           :mask-closable="false"
           @ok="onSubmit"
           @close="handleClose"
           @cancel="handleClose">
    <template #title>
      <div class="gui-padding border-b">
        {{ formState.id ? '修改用户' : '添加用户' }}
      </div>
    </template>
    <div class="gui-padding" style="overflow: hidden auto;height:calc(100vh - 140px)">
      <a-form
          :model="formState"
          name="basic"
          class="mt20"
          layout="vertical"
          style="width: 100%;"
          ref="formRef"
          :rules="rules"
          :label-col=" { style: { width: '150px' } }"
          :wrapper-col="{ span: 24}"
          autocomplete="off"
      >
        <a-row class="flex" gutter="40">
          <a-col :span="12">
          <!-- <a-form-item label="头像" name="avatar">
              <cc-upload v-model="formState.avatar"></cc-upload>
            </a-form-item>-->
            <a-form-item label="登录账号" name="account">
              <a-input v-model:value.trim="formState.account" maxlength="100" placeholder="请填写"/>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="姓名" name="username">
              <a-input v-model:value.trim="formState.username" maxlength="60" placeholder="请填写"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="角色" name="account">
              <a-select v-model:value="roleArr"
                        mode="multiple"
                        style="width: 100%"
                        :disabled="formState.id == 1"
                        placeholder="请选择"
                        @change="handleChangeRole">
                <template v-for="(role,index) in roleList" :key="index">
                  <a-select-option :value="role.id" :label="role.roleName">
                    <span>{{ role.roleName }}</span>
                  </a-select-option>
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="部门" name="departmentId">
              <a-tree-select
                  v-model:value="formState.departmentId"
                  show-search
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="departmentList"
                  tree-node-filter-prop="label"
                  @change="handleSelectDepartment"
                  :field-names="{
                    children: 'children',
                    label: 'name',
                    value: 'id',
                  }"
              >
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="手机" name="phone">
              <a-input v-model:value.trim="formState.phone" maxlength="11" placeholder="请输入手机"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="性别" name="male">
              <a-select v-model:value="formState.male"
                        style="width: 100%" placeholder="请选择">
                <template v-for="(item,index) in maleList" :key="index">
                  <a-select-option :value="item.name" :label="item.name">
                    <span>{{ item.name }}</span>
                  </a-select-option>
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="初始密码" name="password">
              <a-input v-model:value.trim="formState.password" maxlength="16" placeholder="请填写"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="排序(数字越小越靠前)" name="sorted">
              <a-input-number v-model:value.trim="formState.sorted" maxlength="10" placeholder="请填写"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="账户状态" name="status">
              <a-switch v-model:checked="formState.status"
                        :checked-value="1"
                        :un-checked-value="0"
                        checked-children="启动"
                        un-checked-children="停用"/>
            </a-form-item>
          </a-col>

          <a-divider></a-divider>
          <a-col :span="24">
            <a-form-item label="船舶列表">
              <a-checkbox-group v-model:value="checkBoList" @change="handleChangeBo">
                <a-checkbox :value="item.id" v-for="item in chuanboList" :key="item.id">{{ item.zhongWenMing }}
                </a-checkbox>
              </a-checkbox-group>
            </a-form-item>
          </a-col>

          <a-divider></a-divider>
          <a-col :span="24">
            <a-form-item label="船员分组">
              <a-checkbox-group v-model:value="checkZuList" @change="handleChangeFenzu">
                <a-checkbox :value="item.id" v-for="item in chuanboFenzuList" :key="item.id">{{ item.zuMing }}
                </a-checkbox>
              </a-checkbox-group>

            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </a-modal>
</template>
<script setup>
const open = ref(false);
const userState = useStore.userState()
const maleList = computed(() => userState.getParameterList('xb'))
const departmentList = ref([])
const formRef = ref({})
const roleList = ref([])
const roleArr = ref([])
const roleNames = ref([])
const emits = defineEmits(["success"])
const checkBoList = ref([])
const checkBoNames = ref([])
const checkZuList = ref([])
const checkZuNames = ref([])
const chuanboList = ref([])
const chuanboFenzuList = ref([])
const formState = ref({
  account: "",
  password: "123456",
  username: "",
  avatar: "",
  phone: "",
  email: "",
  status: 1,
  admin: 'admin',
  // 传真
  fax: "",
  // 性别
  male: "男",
  // 部门
  departmentId: null,
  // 部门名称
  departmentName: "",
  // 用户工号
  usercode: "",
  // QQ
  qqcode: "",
  // 显示排序
  sorted: 1,
  // 船员IDS分组
  groupIds: "",
  // 船员分组名称列表
  groupNames: "",
  // 船舶IDS列表
  chuanboIds: "",
  // 船舶列表
  chuanboNames: "",
  // 角色IDS列表
  roleIds: "",
  // 角色列表
  roleNames: "",
  // 其他手机号码
  otherphone: "",
  // 子账号
  childrensacount: "",
  // 生日
  birthDay: ""
});

// 验证规则
const rules = {
  account: [{required: true, message: '请输入账号', trigger: 'change'}],
  username: [{required: true, message: '请输入昵称', trigger: 'change'}],
}

const handleSelectDepartment = (value, label) => {
  formState.value.departmentId = value
  formState.value.departmentName = label[0]
}


const handleChangeBo = (checkedValues) => {
  checkBoNames.value = chuanboList.value.filter(option => {
    return checkedValues.includes(option.id)
  }).map(option => option.zhongWenMing);
}

const handleChangeFenzu = (checkedValues) => {
  checkZuNames.value = chuanboFenzuList.value.filter(option => {
    return checkedValues.includes(option.id)
  }).map(option => option.zuMing);
}
const handleChangeRole = (checkedValues) => {
  roleNames.value = roleList.value.filter(option => {
    return checkedValues.includes(option.id)
  }).map(option => option.roleName);
}


const onSubmit = async () => {
  try {
    await formRef.value.validate()

    if (roleArr.value && roleArr.value.length > 0) {
      formState.value.roleIds = roleArr.value.join(",")
      formState.value.roleNames = roleNames.value.join(",")
    }

    if (checkBoList.value && checkBoList.value.length > 0) {
      formState.value.chuanboIds = checkBoList.value.join(",")
      formState.value.chuanboNames = checkBoNames.value.join(",")
    }

    if (checkZuList.value && checkZuList.value.length > 0) {
      formState.value.groupIds = checkZuList.value.join(",")
      formState.value.groupNames = checkZuNames.value.join(",")
    }

    if (formState.value.id) {
      await useUpdateUserApi(formState.value)
    } else {
      await useSaveUserApi(formState.value)
    }
    useMessage().success("操作成功")
    handleClose()
    emits("success")
  } catch (e) {
    useMessage().error(e.msg)
  }
}

const handleLoadDepartmentData = async () => {
  var res = await useLoadDepartmentTreeDataApi()
  departmentList.value = res.data
}

const handleLoadChuaboData = async () => {
  var res = await useLoadChuanBoXinXiBiaoApi()
  chuanboList.value = res.data
}
const handleLoadChuaboFenzuData = async () => {
  var res = await useLoadChuanYuanFenzuBiaoApi()
  chuanboFenzuList.value = res.data
}

const handleAddOpen  = async (record) => {
  open.value = true
  await handleLoadRoleList()
  await handleLoadDepartmentData()
  await handleLoadChuaboData()
  await handleLoadChuaboFenzuData()
  if (record && record.id) {
    const resp = await useGetUserApi(record.id)
    formState.value = resp.data
    roleArr.value = resp.data.roleIds ? resp.data.roleIds?.split(",") : []
    roleNames.value = resp.data.roleNames ? resp.data.roleNames?.split(",") : []
    checkBoList.value = resp.data.chuanboIds ? resp.data.chuanboIds?.split(",") : []
    checkBoNames.value = resp.data.chuanboNames ? resp.data.chuanboNames?.split(",") : []
    checkZuList.value = resp.data.groupIds ? resp.data.groupIds?.split(",") : []
    checkZuNames.value = resp.data.groupNames ? resp.data.groupNames?.split(",") : []
  }
}

const handleLoadRoleList = async () => {
  const resp = await useLoadRoleApi({pageNo: 1, pageSize: 100})
  roleList.value = resp.data.records;
}

const handleClose = () => {
  roleArr.value = []
  roleNames.value = []
  checkBoList.value = []
  checkZuList.value = []
  checkZuNames.value = []
  checkBoNames.value = []
  formState.value = {
    id: "",
    account: "",
    password: "123456",
    username: "",
    avatar: "",
    phone: "",
    email: "",
    status: 1,
    admin: 'admin',
    // 传真
    fax: "",
    // 性别
    male: "男",
    // 部门
    departmentId: null,
    // 部门名称
    departmentName: "",
    // 用户工号
    usercode: "",
    // QQ
    qqcode: "",
    // 显示排序
    sorted: 1,
    // 船员IDS分组
    groupIds: "",
    // 船员分组名称列表
    groupNames: "",
    // 船舶IDS列表
    chuanboIds: "",
    // 船舶列表
    chuanboNames: "",
    // 角色IDS列表
    roleIds: "",
    // 角色列表
    roleNames: "",
    // 其他手机号码
    otherphone: "",
    // 子账号
    childrensacount: "",
    // 生日
    birthDay: ""
  }
  open.value = false
}

defineExpose({
  handleAddOpen
})
</script>

<style lang="scss" scoped>
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }

  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
    overflow: auto;
    border-radius: 0px;
  }

  :where(.css-dev-only-do-not-override-1hsjdkk).ant-modal .ant-modal-header {
    background: transparent;
  }

  .ant-modal-body {
    flex: 1;
  }
}
</style>
